﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LearnWPF.Controls
{
    /// <summary>
    /// NumericUpDown.xaml 的交互逻辑
    /// </summary>
    public partial class NumericUpDown : UserControl
    {
        public NumericUpDown()
        {
            InitializeComponent();
        }

        public decimal Minimum { get; set; } = 0;
        public decimal Maximum { get; set; } = 100;

        /// <summary>
        /// 步进值
        /// </summary>
        public decimal Increment { get; set; } = 1;

        /// <summary>
        /// 小数位
        /// </summary>
        public int DecimalPlaces { get; set; } = 0;

        public decimal Value
        {
            get { return (decimal)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }

        public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(decimal), typeof(NumericUpDown), new UIPropertyMetadata(new decimal(), ValuePropertyChanged));

        private static void ValuePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs arg)
        {
            NumericUpDown control = obj as NumericUpDown;
            decimal Data = (decimal)arg.NewValue;
            control.txtValue.Text = Math.Round(Data, control.DecimalPlaces).ToString();
        }

        private void ButtonAdd_Click(object sender, RoutedEventArgs e)
        {
            Value += Increment;
            if (Value > Maximum)
                Value = Maximum;
        }

        private void ButtonSubtract_Click(object sender, RoutedEventArgs e)
        {
            Value -= Increment;
            if (Value < Minimum)
                Value = Minimum;
        }

        private void txtValue_TextChanged(object sender, TextChangedEventArgs e)
        {
            string txt = txtValue.Text.Trim();
            bool ret = decimal.TryParse(txt, out decimal val);
            if (ret)
            {
                if (val > Maximum) val = Maximum;
                if (val < Minimum) val = Minimum;
                Value = val;
            }
        }       
    }
}
